package cwnu.sapphire.com.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import cwnu.sapphire.com.dto.ScoreDTO;
import cwnu.sapphire.com.entity.Score;
import cwnu.sapphire.com.entity.User;
import cwnu.sapphire.com.service.ScoreService;
import cwnu.sapphire.com.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;
import com.alibaba.excel.EasyExcel;
import cwnu.sapphire.com.dto.ScoreExportDTO;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;

@RestController
@RequestMapping("/api/scores")
public class ScoreController {
    @Autowired
    private ScoreService scoreService;
    
    @Autowired
    private UserService userService;

    @GetMapping
    public List<Score> list() {
        return scoreService.list();
    }

    @GetMapping("/{id}")
    public Score getById(@PathVariable Integer id) {
        return scoreService.getById(id);
    }

    @PostMapping
    public boolean add(@RequestBody Score score) {
        return scoreService.save(score);
    }

    @PutMapping
    public boolean update(@RequestBody Score score) {
        return scoreService.updateById(score);
    }

    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable Integer id) {
        return scoreService.removeById(id);
    }

    /**
     * 获取排序后的成绩列表，包含用户信息
     * 排序规则：
     * 1. 首先按照正确输入字符数（number）降序排列
     * 2. 当正确输入字符数相同时，按照正确率（accuracy）降序排列
     * @return 排序后的成绩列表（包含用户信息）
     */
    @GetMapping("/order")
    public List<ScoreDTO> order() {
        // 1. 获取排序后的成绩列表
        LambdaQueryWrapper<Score> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Score::getNumber)  // 首先按number降序
                   .orderByDesc(Score::getAccuracy) // number相同时按accuracy降序
                   .eq(Score::getDeleteFlag, 0);    // 只查询未删除的记录
        List<Score> scores = scoreService.getBaseMapper().selectList(queryWrapper);
        
        // 2. 转换为DTO并添加用户信息
        return scores.stream().map(score -> {
            ScoreDTO dto = new ScoreDTO();
            BeanUtils.copyProperties(score, dto);
            // 获取用户信息，只保留需要的字段
            User user = userService.getById(score.getUserId());
            if (user != null) {
                User userInfo = new User();
                userInfo.setName(user.getName());
                userInfo.setUsername(user.getUsername());
                userInfo.setGrade(user.getGrade());
                userInfo.setClazz(user.getClazz());
                userInfo.setGender(user.getGender());
                dto.setUser(userInfo);
            }
            return dto;
        }).collect(Collectors.toList());
    }

    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        // 查询排序后的成绩
        List<ScoreDTO> scoreList = this.order();

        // 组装导出数据
        List<ScoreExportDTO> exportList = new ArrayList<>();
        int rank = 1;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        for (ScoreDTO dto : scoreList) {
            ScoreExportDTO exportDTO = new ScoreExportDTO();
            exportDTO.setRank(rank++);
            exportDTO.setName(dto.getUser().getName());
            exportDTO.setUsername(dto.getUser().getUsername());
            exportDTO.setGrade(dto.getUser().getGrade());
            exportDTO.setClazz(dto.getUser().getClazz());
            exportDTO.setGender(dto.getUser().getGender());
            exportDTO.setNumber(dto.getNumber());
            exportDTO.setAccuracy(String.format("%.2f%%", dto.getAccuracy() * 100));
            exportDTO.setCreateTime(dto.getCreateTime().toInstant().atZone(ZoneId.of("Asia/Shanghai")).toLocalDateTime().format(formatter));
            exportList.add(exportDTO);
        }

        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = java.net.URLEncoder.encode("成绩排行榜", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 写出 Excel
        EasyExcel.write(response.getOutputStream(), ScoreExportDTO.class)
                .sheet("成绩排行榜")
                .doWrite(exportList);
    }
} 